package tt.dz.egobus.servicemanager.base.config;

import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import tt.dz.egobus.servicemanager.bean.SpringConfigConstant;
import tt.dz.egobus.servicemanager.business.listener.RedisExpirePubSubHandler;
import tt.dz.egobus.servicemanager.core.executor.StandardThreadExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author Anson
 * @date 17-8-9
 * @name 扩展环境配置
 * @since 1.0.6
 */
@Configuration

public class ExtendContextConfig {



    @Autowired
    @Qualifier(value = "jedisConnectionFactory")
    private JedisConnectionFactory jedisConnectionFactory;


    /**
     * @param
     * @author Anson
     * @date 17-8-9
     * @name 标准的线程执行器
     * @since 1.0.6
     */
    @Bean(name = "standardThreadExecutor")
    ThreadPoolExecutor threadPoolExecutor() {
        return new StandardThreadExecutor();
    }

    @Bean
    SchedulerFactory schedulerFactory() {
        return new StdSchedulerFactory();
    }

    @Bean(name = "expireHandler")
    MessageListenerAdapter listenerAdapter(@Autowired
                                                          RedisExpirePubSubHandler expireHandler) {
        return new MessageListenerAdapter(expireHandler, "expireHandler");
    }

    /**
     * @param threadPoolExecutor
     * @author Anson
     * @date 17-8-24
     * @name redis 监听器容器
     * @since 1.0.6
     */
    @Bean(name = "redisMessageListenerContainer", destroyMethod = "destroy")
    RedisMessageListenerContainer redisMessageListenerContainer(
            @Autowired
            @Qualifier(value = "standardThreadExecutor")
                    ThreadPoolExecutor threadPoolExecutor,
            @Autowired
            @Qualifier(value = "expireHandler")
                    MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(this.jedisConnectionFactory);
        container.setTaskExecutor(threadPoolExecutor);
        container.addMessageListener(listenerAdapter,
                new PatternTopic(SpringConfigConstant.EXPIRE_REDIS_KEY));
        return container;
    }

}
